package artid.com.arttogo.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.activity.ArtCollectorsNewActivity;
import artid.com.arttogo.activity.ArtMallActivity;
import artid.com.arttogo.activity.ArtNewsActivity;
import artid.com.arttogo.activity.ArtNewsDetailActivity;
import artid.com.arttogo.activity.AuctionHomeActivity;
import artid.com.arttogo.activity.CollecterActivity;
import artid.com.arttogo.activity.CollectionDetailPagerActivity;
import artid.com.arttogo.activity.LotSearchActivity;
import artid.com.arttogo.activity.MainActivity;
import artid.com.arttogo.activity.MallDetailPagerActivity;
import artid.com.arttogo.activity.WebViewActivity;
import artid.com.arttogo.adapter.ArtNewsAdapter;
import artid.com.arttogo.adapter.MallListAdapter;
import artid.com.arttogo.bean.GoodsList;
import artid.com.arttogo.bean.HomeFragmentParser;
import artid.com.arttogo.bean.IndexArtwork;
import artid.com.arttogo.bean.NewsList;
import artid.com.arttogo.bean.ShareItem;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUrl;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.pay.ALiPay_Utils;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.MyAdGallery;
import artid.com.arttogo.view.MyListView;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableListView;
import artid.com.arttogo.view.pulllist.PullableScrollView;
import artid.com.arttogo.view.xlistview.PLA_AbsListView;
import artid.com.arttogo.view.xlistview.PLA_AdapterView;
import artid.com.arttogo.view.xlistview.XListView;

/**
 * 项目名称：ArtworkArt
 * 类名称：HomeFragment
 * 类描述：艺来艺往首页
 * 创建人：耿卫斌
 * 创建时间：2017-3-31 上午11:10:22
 */
@SuppressLint("InlinedApi")
public class HomeFragment extends BaseFragment implements OnClickListener {
    private View v;
    private Context mContext;
    private RelativeLayout banndRL;//广告占位布局用于解决触摸引发的滑动冲突
    private ImageView searchBtn;
    private MyAdGallery mMyAdGallery; // 广告控件
    private ViewGroup mMyAdGalleryGroup;//图片轮播指示器控件
    private ArrayList<String> mMyAdGalleryUrl = null;//轮播图片地址
    private RelativeLayout authenticationQueryBtn, auctionHouseBtn, artistBtn, informationBtn, shoppingMallBtn, informationMoreBtn, sousuo;
    private XListView mListView;
    private boolean isRefreshed = false;// 是否刷新
    private int page = 1;
    private int pagesize = 20;
    private MallListAdapter mAdapter;
    private List<HomeFragmentParser.HomeFragmentAdvs> advsList = new ArrayList<HomeFragmentParser.HomeFragmentAdvs>();//广告模块
    private ArrayList<GoodsList> list = new ArrayList<GoodsList>();//推荐商品
    private ArrayList<GoodsList> more_list = new ArrayList<GoodsList>();//推荐商品
    private LinearLayout titlemore;
    private View mHeadView;
    private int dataNum;//数据总条数
    private Boolean isLoad = true;//是否加载数据（默认可以加载）
    private String imgwide;// 请求的图片宽度

    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        v = inflater.inflate(R.layout.fragment_home, null);
        initView();
        return v;
    }

    @Override
    public void onStop() {
        super.onStop();
        mMyAdGallery.stopTimer();
    }

    public void onRestart() {
        mMyAdGallery.startTimer();
    }

    private void initView() {
//        HindStatusBar();master2
        mContext = getActivity();
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "";
//        HindStatusBar();
//        主分支();
        // 头布局
        mHeadView = View.inflate(getActivity(), R.layout.head_homefragment, null);
        banndRL = (RelativeLayout) mHeadView.findViewById(R.id.HomeFragment_banndRL);
        searchBtn = (ImageView) mHeadView.findViewById(R.id.HomeFragment_searchBtn);
        searchBtn.setOnClickListener(this);
        searchBtn.setOnClickListener(this);

        mMyAdGallery = (MyAdGallery) mHeadView.findViewById(R.id.HomeFragment_MyAdGallery);
        mMyAdGallery.setMyOnItemClickListener(onAdGalleryClick);
        mMyAdGalleryGroup = (ViewGroup) mHeadView.findViewById(R.id.HomeFragment_MyAdGallery_viewGroup);
//        authenticationQueryBtn = (RelativeLayout) v.findViewById(R.id.HomeFragment_AuthenticationQueryBtn);
//        authenticationQueryBtn.setOnClickListener(this);
        auctionHouseBtn = (RelativeLayout) mHeadView.findViewById(R.id.HomeFragment_AuctionHouseBtn);
        auctionHouseBtn.setOnClickListener(this);
        artistBtn = (RelativeLayout) mHeadView.findViewById(R.id.HomeFragment_ArtistBtn);
        artistBtn.setOnClickListener(this);
        informationBtn = (RelativeLayout) mHeadView.findViewById(R.id.HomeFragment_InformationBtn);
        informationBtn.setOnClickListener(this);
        shoppingMallBtn = (RelativeLayout) mHeadView.findViewById(R.id.HomeFragment_shoppingMallBtn);
        shoppingMallBtn.setOnClickListener(this);
        informationMoreBtn = (RelativeLayout) mHeadView.findViewById(R.id.HomeFragment_InformationMoreBtn);
        informationMoreBtn.setOnClickListener(this);
        sousuo = (RelativeLayout) v.findViewById(R.id.rel_);
        sousuo.setOnClickListener(this);
        mListView = (XListView) v.findViewById(R.id.HomeFragment_listivew);
        titlemore = (LinearLayout) mHeadView.findViewById(R.id.ll_titlemore);
        mListView.addHeaderView(mHeadView);
        mListView.setVisibility(View.GONE);
        mListView.setPullRefreshEnable(true);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(mIXListViewListener);
        mListView.setOnScrollListener(mOnScrollListener);
        ((MainActivity) getActivity()).registerMyOnTouchListener(myOnTouchListener);  //注册activity触摸事件
        length = (Integer.valueOf(NetUtils.getDisplayMetrics(getActivity()).get(NetUtils.DM_WIDTH)) - NetUtils.dip2px(getActivity(), 40)) / 3 + NetUtils.dip2px(getActivity(), 20);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) titlemore.getLayoutParams();
        lp.height = length;
        titlemore.setLayoutParams(lp);
        int gallaylength = (Integer.valueOf(NetUtils.getDisplayMetrics(getActivity()).get(NetUtils.DM_WIDTH))) / 2;
        LinearLayout.LayoutParams lpl = (LinearLayout.LayoutParams) banndRL.getLayoutParams();
        lpl.height = gallaylength;
        banndRL.setLayoutParams(lp);

        getHomeDate();
        recommendCommodity(true);
        mychannel();
    }


    //实现瀑布流下拉刷新上拉加载监听
    XListView.IXListViewListener mIXListViewListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            // 下拉刷新
            page = 1;
            isRefreshed = true;
            recommendCommodity(true);
        }

        @Override
        public void onLoadMore() {
            // 上拉加载
            page++;
            recommendCommodity(false);
        }
    };
    //实现瀑布流滑动监听
    XListView.OnScrollListener mOnScrollListener = new XListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            Log.d("log", "firstVisibleItem:" + firstVisibleItem + "===visibleItemCount:" + visibleItemCount + "===totalItemCount:" + totalItemCount);
            if (more_list.size() != dataNum && isLoad == true) {
                //-11是数据已经显示一半的时候如果加头了就-12
                //-12是数据已经显示一半的时候（因为加了头所以-12）
                if (page == 1 && firstVisibleItem == (pagesize - 12)) {
                    page++;
                    recommendCommodity(false);
                } else if (((page * pagesize) - 12) == firstVisibleItem) {
                    page++;
                    recommendCommodity(false);
                }
            }
        }
    };

    int length;

    @Override
    public void onClick(View v) {
        Intent intent;
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.rel_:
                //搜索
                intent = new Intent(mContext, LotSearchActivity.class);
                startActivity(intent);
                break;
//            case R.id.HomeFragment_AuthenticationQueryBtn:
//                //鉴证查询
//                Intent intentYsp = new Intent(mContext, WebViewActivity.class);
//                intentYsp.putExtra("type", AppUrl.LOAD_HOMEPAGE_WEB);
//                intentYsp.putExtra("url", AppUrl.JIANZHENG_WEB);
//                startActivity(intentYsp);
//                break;
            case R.id.HomeFragment_AuctionHouseBtn:
                //拍卖行
                intent = new Intent(mContext, AuctionHomeActivity.class);
                startActivity(intent);
                break;
            case R.id.HomeFragment_ArtistBtn:
                //艺术家
                intent = new Intent(mContext, ArtCollectorsNewActivity.class);
                startActivity(intent);
                break;
            case R.id.HomeFragment_InformationBtn:
                //资讯
                intent = new Intent(mContext, ArtNewsActivity.class);
                startActivity(intent);
                break;
            case R.id.HomeFragment_shoppingMallBtn:
                //商城
                intent = new Intent(mContext, ArtMallActivity.class);
                startActivity(intent);
                break;
            case R.id.HomeFragment_InformationMoreBtn:
                //更多商品
                intent = new Intent(mContext, ArtMallActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    /**
     * 轮播图点击事件
     * 0：使用链接地址1：鉴证机构；2：艺术家；3：艺术资讯；4：预约鉴证：5：艺术展厅：6：艺术画廊，7艺术品
     */
    MyAdGallery.MyOnItemClickListener onAdGalleryClick = new MyAdGallery.MyOnItemClickListener() {

        @Override
        public void onItemClick(int curIndex) {
            // TODO Auto-generated method stub
            if (advsList != null && advsList.size() != 0) {
                Intent intent;
                if ("0".equals(advsList.get(curIndex).getType())) {
                    //Web页面
                    ShareItem item = new ShareItem();
                    item.setContent(advsList.get(curIndex).getInfo());
                    item.setId(advsList.get(curIndex).getId());
                    item.setImageUrl(advsList.get(curIndex).getImgurl());
                    item.setTitle(advsList.get(curIndex).getTitle());
                    item.setUrl(advsList.get(curIndex).getLinkurl());
                    intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra("url", advsList.get(curIndex).getLinkurl());
                    intent.putExtra("title", advsList.get(curIndex).getTitle());
                    intent.putExtra("type", AppUrl.LOAD_WEB_WITH_TITLE);
                    intent.putExtra("share", item);
                    startActivity(intent);
                } else if ("2".equals(advsList.get(curIndex).getType())) {
                    //艺术家
                    intent = new Intent(mContext, CollecterActivity.class);
                    intent.putExtra("id", advsList.get(curIndex).getId());
                    startActivity(intent);
                } else if ("3".equals(advsList.get(curIndex).getType())) {
                    //艺术资讯
                    intent = new Intent(mContext, ArtNewsDetailActivity.class);
                    intent.putExtra("id", advsList.get(curIndex).getId());
                    startActivity(intent);
                } else if ("4".equals(advsList.get(curIndex).getType())) {
                    //预约鉴证
                } else if ("7".equals(advsList.get(curIndex).getType())) {
                    //艺术品
                    intent = new Intent(mContext, CollectionDetailPagerActivity.class);
                    intent.putExtra("id", advsList.get(curIndex).getId());
                    intent.putExtra("titleName", advsList.get(curIndex).getTitle());
                    startActivity(intent);
                }

            }
        }
    };

    /**
     * 商城Item点击事件
     */
    private void setItemClick(final String json) {
        mListView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, MallDetailPagerActivity.class);
                intent.putExtra("id", json);
                intent.putExtra("index", position - 2);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取首页数据
     */
    private void getHomeDate() {
        VolleyBasic.getInstance(getActivity()).post(Cache.HOME_URL,
                VolleyMap.getInstance().advsArtist(),
                HomeFragmentParser.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        HomeFragmentParser mBean = new HomeFragmentParser();
                        JSONObject ob = null;
                        try {
                            ob = new JSONObject(vd.getJson());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        mBean.parse(ob);
                        advsList = mBean.getAdvs();
                        if (advsList != null && advsList.size() != 0) {
                            //获取轮播图数据
                            mMyAdGalleryUrl = new ArrayList<String>();
                            for (int i = 0; i < advsList.size(); i++) {
                                mMyAdGalleryUrl.add(advsList.get(i).getImgurl());
                            }
                            String[] imageData = new String[mMyAdGalleryUrl.size()];
                            for (int i = 0; i < mMyAdGalleryUrl.size(); i++) {
                                imageData[i] = mMyAdGalleryUrl.get(i).toString();
                            }
                            mMyAdGallery.startNotFxed(mContext, imageData, null, 3000, mMyAdGalleryGroup, R.drawable.point_pressed, R.drawable.point_unpressed);
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                    }
                });
    }

    void mychannel() {
        VolleyBasic.getInstance(getActivity()).post(Cache.mychannel,
                VolleyMap.getInstance().mychannel(AppUtil.getUser().getToken()),
                IndexArtwork.class, new VolleyCallback() {
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        System.out.println("mychannel=" + vd.getJson());
                        MySharedPreferences.getMySharedPreferences(getActivity()).setValue("mychannel", vd.getJson());
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    /**
     * 推荐商品
     *
     * @param isLoadDialog
     */
    JSONObject mainJson;
    JSONArray mainJSONArr;

    private void recommendCommodity(Boolean isLoadDialog) {
        isLoad = false;
        if (isLoadDialog) {
            VolleyBasic.showLoding(getActivity());
        }
        VolleyBasic.getInstanceNoDialog(getActivity()).post(Cache.goodsIndex, VolleyMap.getInstance().goodsIndex(
                page, pagesize, imgwide), GoodsList.class,
                new VolleyCallback() {
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        isLoad = true;
                        mListView.stopRefresh();
                        mListView.stopLoadMore();
                        if (page == 1) {
                            try {
                                JSONObject jsonObject = new JSONObject(vd.getJson());
                                dataNum = jsonObject.getInt("num");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        list = (ArrayList<GoodsList>) vd.getList();
                        if (isRefreshed == true) {
                            more_list.clear();
                            isRefreshed = false;
                        }
                        if (!list.isEmpty()) {
                            more_list.addAll(list);
                        }
                        JSONObject jsonString = vd.getObj();
                        JSONArray jsonArray = jsonString.optJSONArray("data");
                        if (page != 1) {
                            try {
                                if (jsonArray == null) {
                                    return;
                                }
                                for (int i = 0; i < jsonArray.length(); i++) {

                                    mainJSONArr.put(jsonArray.get(i));

                                }
                                mainJson.remove("data");
                                mainJson.put("data", mainJSONArr);
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            mAdapter.addlist(list);
                            setItemClick(mainJson.toString());
                            return;
                        }
                        mListView.setVisibility(View.VISIBLE);
                        mainJson = jsonString;
                        mainJSONArr = jsonArray;
                        mAdapter = new MallListAdapter(mContext);
                        mAdapter.setdata(list);
                        mListView.setAdapter(mAdapter);
                        setItemClick(vd.getJson());
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        isLoad = true;
                        mListView.stopRefresh();
                        mListView.stopLoadMore();
                    }
                });
    }


    /**
     * Fragment触摸事件
     */
    private int startX = 0;//手指按下的初始位置
    private int startY = 0;
    private boolean start = true;
    public MainActivity.MyOnTouchListener myOnTouchListener = new MainActivity.MyOnTouchListener() {

        @Override
        public boolean onTouch(MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    //手指按下
                    startX = (int) event.getX();
                    startY = (int) event.getY();
                    PullableScrollView.isSlide = false;
                    break;
                case MotionEvent.ACTION_UP:
                    //手指已抬起
                    PullableScrollView.isSlide = true;
                    break;
                case MotionEvent.ACTION_MOVE:
                    //判断是否有轮播图
                    if (banndRL != null) {
                        //判断是否在滑动广告
                        if (startY < banndRL.getHeight() && ((startX - event.getX()) > 10 || (startX - event.getX()) < -10)) {
                            PullableScrollView.isSlide = false;
                        } else {
                            PullableScrollView.isSlide = true;
                        }
                    } else {
                        PullableScrollView.isSlide = true;
                    }
                    break;

                default:
                    break;
            }
            return false;
        }
    };

    //透明状态栏
    private void HindStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getActivity().getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //不可见

        } else {
            //当前可见
            mMyAdGallery.startTimer();
        }
    }
}
